﻿using System;
using System.Collections.Generic;
using System.Threading;
using NUnit;
using NUnit.Framework;
using Rhino.Mocks;

namespace mForum.Core.Tests.Infrastructure.EventAggregator
{
    using mForum.Core.Infrastructure.EventAggregator;

    [TestFixture]
    public class EventAggregatorTest
    {
        private IEventAggregator _eventAggregator;
        private IListenerService _subscriptionService;

        [SetUp]
        public void SetUp()
        {
            _subscriptionService = MockRepository.GenerateMock<IListenerService>();
            _eventAggregator = new EventAggregator(new SynchronizationContext(), _subscriptionService);
        }

        [Test]
        public void can_send_messages_to_listeners()
        {
            var Handler1 = MockRepository.GenerateMock<IListenTo<TestEvent>>();
            var Handler2 = MockRepository.GenerateMock<IListenTo<TestEvent>>();
            var Handler3 = MockRepository.GenerateMock<IListenTo<TestEvent>>();

            List<IListenTo<TestEvent>> listenerList = new List<IListenTo<TestEvent>> { Handler1, Handler2, Handler3 };
            TestEvent testEvent = new TestEvent();

            _subscriptionService.Stub(l => l.GetListeners<TestEvent>()).Return(listenerList);

            Handler1.Expect(x => x.Handle(testEvent)).Repeat.Once();
            Handler2.Expect(x => x.Handle(testEvent)).Repeat.Once();
            Handler3.Expect(x => x.Handle(testEvent)).Repeat.Once();

            _eventAggregator.SendMessage(testEvent);

            Handler1.VerifyAllExpectations();
            Handler2.VerifyAllExpectations();
            Handler3.VerifyAllExpectations();
        }

        public class TestEvent : IEvent { }
    }
}
